//
//  RTJUserInfoController.m
//  RuiTaiJinProject
//
//  Created by jayson on 2018/12/1.
//  Copyright © 2018年 leewei. All rights reserved.
//

#import "RTJUserInfoController.h"
#import "RTJUserInfoCell.h"
#import "RTJUseRrealNameController.h"
#import "RTJForgetPassWordController.h"
#import "RTJBindPayCardController.h"
#import "RTJRiskAssessmentController.h"
#import "RTJRiskResultController.h"
#import "RTJMyBankListController.h"
#import "SDImageCache.h"
@interface RTJUserInfoController ()<UserInfoButtonActionDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic)  NSArray *bankListArr;
@property (nonatomic,strong) NSMutableArray<UIImage *> * arrImgs;

@end

@implementation RTJUserInfoController

-(NSMutableArray<UIImage *> *)arrImgs {
    if (!_arrImgs) {
        _arrImgs = [NSMutableArray new];
    }
    
    return _arrImgs;
}

-(void)viewWillAppear:(BOOL)animated{
    
    
    if ([RTJUserTool isLogin]) {
       
        //获取用户银行卡列表
        [self userbanklist];
        
        [RTJNetWork asyncRequestWithURL:@"user/get_user_info" params:@{@"id":[RTJUserTool getTheUserModel].user_id} method:POST zxCompletion:^(id data, NSInteger status, BOOL success, NSString *errorMsg) {
            
            if (success) {
                
                if ([data[@"status"]integerValue] == 1) {
                    
                    [RTJUserTool saveTheUserInfo:data[@"data"]];
                    
                    [self.tableView reloadData];
                    
                }else{
                    
                    [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",errorMsg]];

                }
                
            }else{
                
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",errorMsg]];

            }
            
            
        }];
        
    }else{
        
        [self.tableView reloadData];
        
    }
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBarHidden = NO;
    self.title = @"个人中心";
    self.tableView.tableFooterView=[UIView new];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.estimatedRowHeight=300;
    
    
}

-(void)userbanklist{
    
//    [SVProgressHUD showWithStatus:nil];
//    [self.view showEmptyViewWithStr:@"" image:nil callback:nil];
    
    [RTJNetWork asyncRequestWithURL:@"user/bank_list" params:@{@"is_quick":@"0"} method:GET zxCompletion:^(id data, NSInteger status, BOOL success, NSString *errorMsg) {
        
//        [SVProgressHUD dismiss];
//        [self.view removeEmptyView];
        
        if (success) {
            
            if ([data[@"status"]integerValue] == 1) {
                
                self.bankListArr = data[@"data"];
                [self.tableView reloadData];
                
            }else{

                 NSLog(@"===%@",[NSString stringWithFormat:@"%@",data[@"msg"]]);
                
            }
            
        }else{
            
                NSLog(@"===%@",[NSString stringWithFormat:@"%@",errorMsg]);
            
        }
        
    }];
    
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return UITableViewAutomaticDimension;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * ID = @"RTJUserInfoCell";
    
    RTJUserInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
        
        if (!cell) {
            
            cell = [[NSBundle mainBundle] loadNibNamed:@"RTJUserInfoCell" owner:self options:nil][0];
        }
    
//    cell.isBindBankCard = _bankListArr.count!=0 ? YES : NO;
    cell.bankArr = _bankListArr;
    cell.delegate = self;
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    return  cell;
    
}

-(void)userInfobuttonOfTagsAction:(NSInteger)buttonOfTag{
    
    if (buttonOfTag == 10) {
        
        RTJUseRrealNameController *vc = [[RTJUseRrealNameController alloc]init];
        vc.isChangeUserName = YES;
        [self.navigationController pushViewController:vc animated:YES];
        
    }else if (buttonOfTag == 20){
        
    }else if (buttonOfTag == 30){
        
        if ([RTJUserTool getTheUserModel].idcardpassed == 0) {
            
            RTJUseRrealNameController *vc = [[RTJUseRrealNameController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }
        
    }else if (buttonOfTag == 40){
        
            if (_bankListArr.count == 0) {
            
            RTJBindPayCardController *vc = [[RTJBindPayCardController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
            
        }else{
            
            RTJMyBankListController *vc = [[RTJMyBankListController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
  
        }
        
    }else if (buttonOfTag == 50){
        
        if ([RTJUserTool getTheUserModel].is_risk == 0) {
            
            RTJRiskAssessmentController *risk =  [[RTJRiskAssessmentController alloc]init];
            [self.navigationController pushViewController:risk animated:YES];
            
        }else{
            
            RTJRiskResultController *risk =  [[RTJRiskResultController alloc]init];
            [self.navigationController pushViewController:risk animated:YES];
        }
        
    }else if (buttonOfTag == 60){
        
        RTJForgetPassWordController *vc = [[RTJForgetPassWordController alloc]init];
        vc.title = @"修改登录密码";
        vc.isPayPassWord = NO;
        vc.isForgetPassWord = NO;
        [self.navigationController pushViewController:vc animated:YES];
        
    }else if (buttonOfTag == 70){
       
        RTJForgetPassWordController *vc = [[RTJForgetPassWordController alloc]init];
        vc.title = @"修改支付密码";
        vc.isPayPassWord = YES;
        vc.isForgetPassWord = NO;
        [self.navigationController pushViewController:vc animated:YES];
        
    }else if (buttonOfTag == 80){
        
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"确定退出登陆？" preferredStyle:UIAlertControllerStyleAlert];
        
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            
            [SVProgressHUD showWithStatus:nil];
            [RTJNetWork asyncRequestWithURL:@"user/logout" params:nil method:POST zxCompletion:^(id data, NSInteger status, BOOL success, NSString *errorMsg) {
                
                [SVProgressHUD dismiss];
                
                if (success) {
                    
                    if ([data[@"status"]integerValue] == 1) {
                        
                        [RTJUserTool loginOut];
                        [self.navigationController popViewControllerAnimated:YES];
                        
                    }else{
                        
                        [RTJUserTool loginOut];
                        [self.navigationController popViewControllerAnimated:YES];
                        
                        
                    }
                    
                }else{
                    
                    [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"退出失败:%@",errorMsg]];
                }
                
            }];
            
        }]];
        
        [self presentViewController:alertController animated:YES completion:nil];
     

    }else if (buttonOfTag == 90){
        
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            
            
            if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
                UIAlertController *alert = [self moreSheetAlert];
                [self presentViewController:alert animated:YES completion:nil];
                
            }else {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *takephoto = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                    [self takePhoto];
                    
                }];
                UIAlertAction *localphoto = [UIAlertAction actionWithTitle:@"从相册中选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                    [self LocalPhoto];
                    
                }];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                
                [alert addAction:takephoto];
                [alert addAction:localphoto];
                [alert addAction:cancelAction];
                [self presentViewController:alert animated:YES completion:nil];
                
            }
            
        }else{
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *takephoto = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                NSLog(@"请在真机上测试");
                return;
            }];
            UIAlertAction *localphoto = [UIAlertAction actionWithTitle:@"从相册中选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                [self LocalPhoto];
                
            }];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            
            [alert addAction:takephoto];
            [alert addAction:localphoto];
            [alert addAction:cancelAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
        
        
    }
    
}

-(UIAlertController *)moreSheetAlert{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"拍照"
                                                        style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction * _Nonnull action) {
                                                          [self takePhoto];
                                                      }]];
    
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"从相册中选择"
                                                        style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction * _Nonnull action) {
                                                          [self LocalPhoto];
                                                          
                                                      }]];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消"
                                                        style:UIAlertActionStyleCancel
                                                      handler:nil]];
    
    return alertController;
}


//开始拍照
-(void)takePhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        picker.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
        [self presentViewController:picker animated:YES completion:nil];
        picker =nil;
        
        
    }else{
        [ SVProgressHUD showErrorWithStatus:@"无法打开照相机!"];
    }
}

//打开本地相册
-(void)LocalPhoto
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    picker.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentViewController:picker animated:YES completion:nil];
    picker =nil;
}
//当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        // 关闭相册界面
        [picker dismissViewControllerAnimated:YES completion:nil];
        UIImage* image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
        [self.arrImgs addObject:image];
        

        NSMutableArray *picData = [NSMutableArray array];
        for (UIImage *image in _arrImgs) {
            NSData * pictureData = UIImageJPEGRepresentation(image, 0.5);
            [picData addObject:pictureData];
        }
        
        NSString * fileName = @"";
        NSInteger count = [picData count];
        for (NSInteger idx = 0; idx < count; idx ++) {

            fileName = [NSString stringWithFormat:@"Image%ld.jpg", idx + 1];
        }
        //上传图片
        [SVProgressHUD showWithStatus:@"头像上传中..."];
        [RTJNetWork uploadImageToResourceURL:@"user/upload_avatar" images:picData params:@{@"avatar_file":fileName} zxCompletion:^(id data, NSInteger status, BOOL success, NSString *errorMsg) {
            
            if (success) {
                
                if ([data[@"status"]integerValue] == 1) {
                    
                    [SVProgressHUD showSuccessWithStatus:@"更改头像成功"];

                    int x = arc4random() % 10000000;
                    
                    NSString *avatarurl =  [NSString stringWithFormat:@"%@?%d", data[@"data"][@"avatar"],x];
                    NSUserDefaults *avatar = [NSUserDefaults standardUserDefaults];
                    [avatar setObject:avatarurl forKey:@"avatarurl"];
                    [avatar synchronize];
                    

//                    [[SDImageCache sharedImageCache]removeImageForKey:[RTJUserTool getTheUserModel].avatar withCompletion:nil];
                    
                    RTJUserModel *model = [RTJUserTool getTheUserModel];
                    model.avatar = [NSString stringWithFormat:@"%@", data[@"data"][@"avatar"]];
                    [RTJUserTool saveUserInfo:model];
                    [self.tableView reloadData];

                    [self.arrImgs removeAllObjects];
                    
                }else{
                    
                    [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"更改头像失败:%@", data[@"msg"]]];
                    [self.arrImgs removeAllObjects];

                }
                
            }else{
                
                [self.arrImgs removeAllObjects];
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"更改头像失败:%@", errorMsg]];
            }
            
        }];
       
    }
}

//点击取消键调用该代理方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}


@end
